<template>
  <div>
    <el-card>
      <el-row>
        <el-col>基本资料</el-col>
      </el-row>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 表单区域 -->
      <el-form ref="userInfoRef" :rules="rules" :model="userInfo" label-width="100px">
        <el-form-item label="登录名称">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="userInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFn">提交修改</el-button>
          <el-button @click="resetFn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserInfoAPI, updateUserInfoAPI } from '@/api'

export default {
  data () {
    return {
      userInfo: {},
      userInfoRef: '',
      rules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{1,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取用户信息
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    async getUserInfo () {
      const { data: res } = await getUserInfoAPI()
      console.log(res)
      this.userInfo = res.data
    },
    submitFn () {
      this.$refs.userInfoRef.validate(async valid => {
        if (!valid) {
          return false
        }
        const { data: res } = await updateUserInfoAPI(this.userInfo)
        console.log(res)
        if (res.code !== 0) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.$store.dispatch('initUserInfo')
      })
    },
    resetFn () {
      this.$refs.userInfoRef.resetFields()
    }

  }
}
</script>

<style lang="less" scoped>
.el-input{
  width: 500px;
  border: 2px solid #fff;
}
</style>
